package win.bigwhale.library.db.daoimp;

import java.lang.reflect.ParameterizedType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import win.bigwhale.library.db.bean.User;
import win.bigwhale.library.db.dao.UserDao;
import win.bigwhale.library.db.daohelper.WhaleDaoHelper;

public class UserDaoImp extends BaseDaoImp<User> implements UserDao {
	private Class<?> user;
	private PreparedStatement statement;
	private String sql;
	private ResultSet resultSet;

	public UserDaoImp() {
		ParameterizedType type = (ParameterizedType)getClass().getGenericSuperclass();
		user = (Class<?>) type.getActualTypeArguments()[0];
	}

	@Override
	public ArrayList<User> findAll() {
		ArrayList<User> userlist = new ArrayList<>();
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("select * from ").append(user.getSimpleName());
		sql = stringBuffer.toString();
		try {
			statement = WhaleDaoHelper.getPreparedStatement(sql);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt("id"));
				user.setFirstName(resultSet.getString("first_name"));
				user.setLastName(resultSet.getString("last_name"));
				user.setGender(resultSet.getString("gender"));
				user.setAge(resultSet.getInt("age"));
				user.setBirth(resultSet.getDate("birth"));
				user.setRole(resultSet.getString("role"));
				userlist.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userlist;
	}

}
